package org.example.controller;


import org.example.utils.AllOssUtil;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private Environment env;
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        // 把文件的内容存储到本地磁盘上
        String orginalFilename = file.getOriginalFilename(); // 获取文件名
        String fileSuffix = orginalFilename.substring(orginalFilename.lastIndexOf(".")); // 文件名后缀
        String filename = "longyu12_" + UUID.randomUUID() ;

        // 获取oss相关配置
        String ENDPOINT = env.getProperty("oss.ENDPOINT");
        String ACCESS_KEY_ID = env.getProperty("oss.ACCESS_KEY_ID");
        String ACCESS_KEY_SECRET = env.getProperty("oss.ACCESS_KEY_SECRET");
        String BUCKET_NAME = env.getProperty("oss.BUCKET_NAME");

        String url = AllOssUtil.uploadFile(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET, BUCKET_NAME, filename+fileSuffix, file.getInputStream());
        // file.transferTo(new File("E:\\Project\\longyu12\\images\\" + filename + fileSuffix)); 将文件写入本地磁盘
        return Result.success(url);
    }
}
